package Queuedemo;

/**
 * Created with IntelliJ IDEA.
 * Description:使用双向链表实现的普通队列
 * User: 87111
 * Date: 2025-09-07
 * Time: 18:44
 */
public class MyQueue {
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    public ListNode last;

    //入队操作(尾插)
    public void offer(int key) {
        ListNode node = new ListNode(key);
        if(isEmpty()) {
            head = node;
            last = node;
            return;
        }
        last.next = node;
        node.prev = last;
        last = node;
    }

    //出队操作
    public int poll() {
        if(isEmpty()) {
            return -1;
        }
        int val = head.val;
        if(head.next == null) {
            head = null;
            last = null;
        }else {
            head.next.prev = null;
            head = head.next;
        }
        return val;
    }

    //查询头节点的值
    public int peek() {
        if(isEmpty()) {
            return -1;
        }
        return head.val;
    }

    //判断队列是否为空
    public boolean isEmpty() {
        if(head == null && last == null) {
            return true;
        }
        return false;
    }

    //获取队列的大小
    public int size() {
        if(isEmpty()) {
            return -1;
        }
        ListNode node = head;
        int size = 0;
        while(head != null) {
            size++;
        }
        return size;
    }

}
